<template>
    <div style="width: 95%;margin: auto;">
        <!-- 
        :inline :把el-form-item 设置 行内元素
         -->
        <el-form :inline="true" :model="newsFrom" class="demo-form-inline">
            <el-form-item style="width: 180px;">
                <el-input v-model="newsFrom.title" placeholder="请输入标题" clearable />
            </el-form-item>
            <el-form-item style="width: 180px;">
                <el-select v-model="newsFrom.type" placeholder="请选择类型" clearable>
                    <el-option label="优惠通知" value="优惠通知" />
                    <el-option label="上架通知" value="上架通知" />
                    <el-option label="下架通知" value="下架通知" />
                </el-select>
            </el-form-item>
            <el-form-item style="width: 180px;">
                <el-select v-model="newsFrom.status" placeholder="是否过时" clearable>
                    <el-option label="未过时" value="0" />
                    <el-option label="以过时" value="1" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-date-picker v-model="newsFrom.createtime" type="date" placeholder="何时前发布" clearable />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" :icon="Search" @click="clickfindAll(1)" style="width: 100px;">查询</el-button>
            </el-form-item>
        </el-form>
    </div>

    <div v-if="store.userinfo.type == '管理员'">
        <span style="width: 95%;margin-left: 35px;">
            <el-button type="primary" :icon="Plus" @click="addNews()">发布新闻</el-button>
        </span>
        <span style="width: 95%;margin-left: 10px;">
            <el-button type="primary" :icon="Delete" @click="batchedDeleteByIds()">批量删除</el-button>
        </span>
    </div>


    <el-table :data="newsPage.allNews" style="width: 95%; margin: auto;" @selection-change="handleSelectionChange"
        :default-sort="{ prop: 'createtime', order: 'descending' }" ref="elTableRef">
        <!-- 添加复选框选项 -->
        <el-table-column type="selection" width="55" />
        <el-table-column label="创建时间" prop="createtime" sortable width="150px" fixed />
        <el-table-column label="编号" prop="nid" width="150px" />
        <el-table-column label="标题" prop="title" width="150px" />
        <el-table-column label="作者" prop="author" width="150px" />
        <el-table-column label="备注" prop="remarks" width="150px" />
        <el-table-column label="类型" prop="type" width="150px">
            <!-- 插槽 -->
            <template #default="scope">
                <el-tag v-if="scope.row.type == '优惠通知'" type="primary">优惠通知</el-tag>
                <el-tag v-else-if="scope.row.type == '上架通知'" type="success">上架通知</el-tag>
                <el-tag v-else type="danger">下架通知</el-tag>
            </template>
        </el-table-column>
        <el-table-column label="是否过时" prop="status" width="150px">
            <!-- 插槽 -->
            <template #default="scope">
                <el-tag v-if="scope.row.status == 0" type="primary">未过时</el-tag>
                <el-tag v-else type="danger">已过时</el-tag>
            </template>
        </el-table-column>
        <el-table-column width="150px" fixed="right" label="操作">
            <template #default="scope">
                <el-tooltip v-if="store.userinfo.type == '管理员'" class="box-item" effect="dark" content="修改新闻信息"
                    placement="bottom">
                    <el-button type="primary" :icon="Edit" circle @click="handleEdit(scope.$index, scope.row)" />
                </el-tooltip>
                <el-tooltip v-if="store.userinfo.type == '管理员'" class="box-item" effect="dark" content="删除/恢复"
                    placement="bottom">
                    <el-button type="danger" :icon="Delete" circle @click="handleDelete(scope.row)" />
                </el-tooltip>
                <el-tooltip class="box-item" effect="dark" content="查看新闻" placement="bottom">
                    <el-button type="success" :icon="Search" circle @click="viewnews(scope.row)" />
                </el-tooltip>
            </template>
        </el-table-column>
    </el-table>
    <!-- 分页插件 -->
    <div style="width: 95%;margin: 10px auto;">
        <el-pagination background layout="prev, pager, next" v-model:page-size="newsFrom.pageSize"
            v-model:current-page="newsFrom.pageNum" :total="newsFrom.total" @current-change="findAll" />
    </div>



    <!-- 新闻详情弹窗 -->
    <el-dialog v-model="newsDetailsDialog.isDialogShow" title="新闻详情" width="700px" :close-on-click-modal="false">
        <!-- 弹窗内容区：网格布局展示字段，结构清晰 -->
        <div class="news-detail-container">
            <!-- 新闻标题 -->
            <div class="detail-item">
                <span class="detail-label">标题：</span>
                <span class="detail-value" style="font-weight: 600;">{{ newsDetailsDialog.news.title || '暂无时间' }}</span>
            </div>

            <!-- 新闻作者 -->
            <div class="detail-item">
                <span class="detail-label">作者：</span>
                <span class="detail-value">{{ newsDetailsDialog.news.author || '暂无时间' }}</span>
            </div>

            <!-- 发布时间（格式化展示，避免原始时间戳） -->
            <div class="detail-item">
                <span class="detail-label">发布时间：</span>
                <span class="detail-value">{{ newsDetailsDialog.news.createtime || '暂无时间' }}</span>
            </div>

            <!-- 新闻正文（换行展示，添加内边距） -->
            <div class="detail-item content-item">
                <span class="detail-label">正文：</span>
                <div style=" display: block; width: 100%; max-height: 300px; overflow-y: auto; padding: 12px 16px; line-height: 1.8;
                    font-size: 14px; color: #303133; background: #f5f7fa; border: 1px solid #e4e7ed; border-radius: 4px; white-space: pre-wrap;
                     box-sizing: border-box;">
                    {{ newsDetailsDialog.news.content || '暂无正文' }}
                </div>
            </div>
        </div>

        <!-- 弹窗底部按钮：仅保留“关闭”按钮（无其他功能） -->
        <template #footer>
            <el-button @click="newsDetailsDialog.isDialogShow = false">
                关闭
            </el-button>
        </template>
    </el-dialog>

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="newsEditDialog.isShow" :title="newsEditDialog.isAdd ? '发布新闻' : '修改新闻'" width="600px"
        :close-on-click-modal="false">
        <el-form :model="newsEditDialog.form" label-width="70px" style="padding-right:20px">
            <el-form-item label="标题"><el-input v-model="newsEditDialog.form.title" /></el-form-item>
            <el-form-item label="作者"><el-input v-model="newsEditDialog.form.author" /></el-form-item>
            <el-form-item label="类型">
                <el-select v-model="newsEditDialog.form.type" style="width:100%">
                    <el-option label="优惠通知" value="优惠通知" />
                    <el-option label="上架通知" value="上架通知" />
                    <el-option label="下架通知" value="下架通知" />
                </el-select>
            </el-form-item>
            <el-form-item label="备注"><el-input v-model="newsEditDialog.form.remarks" /></el-form-item>
            <el-form-item label="正文"><el-input v-model="newsEditDialog.form.content" type="textarea"
                    :rows="6" /></el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="newsEditDialog.isShow = false">取消</el-button>
            <el-button type="primary" @click="submitNews">保存</el-button>
        </template>
    </el-dialog>
</template>
<script setup>
//1.引入ref和reactive
import { ref, reactive, onMounted } from 'vue';
import request from '../utils/request';
import { Delete, Edit, Plus, Search, Setting } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
//引入useCounterStore实例
import { useUserStore } from '../stores/userStore'
//创建stote实例
let store = useUserStore();
// 定义 el-table 的 ref
const elTableRef = ref();
//存放后端查询用户数据变量
let newsPage = reactive({
    allNews: [],

})
//声明一个对象，用于条件查询
let newsFrom = ref({
    pageNum: 0,
    pageSize: 5,
    total: 0
})
//声明一个数组用来存放批量删除数组
let newsArray = reactive([

])
//声明新闻详情弹窗所需要的属性
let newsDetailsDialog = reactive({
    isDialogShow: false,
    news: {
        title: '',
        author: '',
        createtime: '',
        content: ''
    }
})
//声明新增或修改对话框所需要的属性
const newsEditDialog = reactive({
    isShow: false,
    isAdd: true,
    form: { nid: null, title: '', author: '', type: '', remarks: '', content: '' }
})
/* -------------- 新增/编辑 -------------- */
// 新增按钮
const addNews = () => {
    newsEditDialog.isAdd = true
    newsEditDialog.form = { nid: null, title: '', author: '', type: '', remarks: '', content: '' }
    newsEditDialog.isShow = true
}
// 修改按钮
const handleEdit = (idx, row) => {
    newsEditDialog.isAdd = false
    // 回显本行
    newsEditDialog.form = { ...row }
    newsEditDialog.isShow = true
}
// 新增修改对话框中的保存按钮
const submitNews = async () => {          
    const url = newsEditDialog.isAdd ? '/news/add' : '/news/update'
    const method = newsEditDialog.isAdd ? 'post' : 'put'
    const res = await request[method](url, newsEditDialog.form)
    if (res.data.success) {
        ElMessage.success(newsEditDialog.isAdd ? '发布成功' : '修改成功')
        newsEditDialog.isShow = false
        // 刷新当前页
        findAll(newsFrom.value.pageNum) 
    } else {
        ElMessage.error(res.data.message || '操作失败')
    }
}
//select选择发生变化
const handleSelectionChange = (newSelection) => {
    newsArray = newSelection;
}
//批量删除
const batchedDeleteByIds = async () => {
    let res = await request.put('/news/updateByNews', newsArray);
    if (res.data.success) {
        //1.刷新页面
        findAll(newsFrom.value.pageNum);
        elTableRef.value.clearSelection();
        ElMessage.success("操作成功");
    } else {
        ElMessage.error("操作失败");
    }
}
//删除单个新闻
const handleDelete = async (row) => {
    let res = await request.put('/news/delete', row);
    if (res.data.success) {
        //1.刷新页面
        findAll(newsFrom.value.pageNum);
        ElMessage.success("操作成功");
    } else {
        ElMessage.error("操作失败");
    }
}

//显示新闻详情按钮
const viewnews = (news) => {
    //初始化新闻详情
    newsDetailsDialog.news.title = news.title || '';
    newsDetailsDialog.news.author = news.author || '';
    newsDetailsDialog.news.createtime = news.createtime || '';
    newsDetailsDialog.news.content = news.content || '';
    newsDetailsDialog.isDialogShow = true;
}

//根据条件查询新闻信息
const findAll = async (currentpage) => {
    newsFrom.value.pageNum = currentpage;
    let res = await request.post("/news/queryCondition", newsFrom.value);
    // console.log(res);
    if (res.data.success) {        
        newsPage.allNews = res.data.data.list;
        newsFrom.value.pageNum = res.data.data.pageNum;
        newsFrom.value.pageSize = res.data.data.pageSize;
        newsFrom.value.total = res.data.data.total;
        return true;
    } else {
        return false;
    }
}
//点击条件查询按钮
const clickfindAll = () => {
    if (findAll(1)) {
        ElMessage.success("查询成功")
    } else {
        ElMessage.success("查询失败")
    }
}

//当实例挂载到元素之后触发onMounted
onMounted(() => {
    //1.调用方法实现，查询用户数据
    findAll(1);
})
</script>